
/** 获取lrc歌词 */
function fetchLrc() {
  fetch('./assets/浩然H_R - 年少的你啊.lrc').then((res) => {
    if (res.status === 200) {
      res.text().then(lrc => {
        parseLrc(lrc)
      })
    }
  }).catch(reason => {
    console.info(reason)
  })
}

/**
 * 解析歌词并渲染
 * @param {*} lrc 
 */
function parseLrc(lrc) {
  if (!lrc) {
    return
  }
  /** 时间+歌词 { timestamp, lrc } */
  const lyricList = []
  // 时间正则表达式
  const timeReg = /\[(\d{2}):(\d{2}).(\d{2})]/
  const lines = lrc.split('\n')
  for (let index = 0; index < lines.length; index++) {
    const line = lines[index]
    const matched = timeReg.exec(line)
    if (line && matched) {
      lyricList.push({
        timestamp: parseInt(matched[1])*60 + parseInt(matched[2]) + parseInt(matched[3]) / 1000,
        lrc: line.replace(timeReg, '').trim()
      })
    }
  }
  const lyricUlDOM = document.getElementById('lyric')
  if (lyricUlDOM) {
    // 渲染歌词
    const fragments = document.createDocumentFragment()
    lyricList.forEach((lyric, index) => {
      const li = document.createElement('li')
      li.textContent = lyric.lrc
      li.setAttribute('index', index)
      li.setAttribute('time', lyric.timestamp)
      fragments.appendChild(li)
    })
    lyricUlDOM.append(fragments)
    // 监听播放器
    const audio = document.getElementById('audio')
    audio.addEventListener('timeupdate', function() {
      const currentTime = this.currentTime
      // 找到当前播放的第几句歌词
      let currentIndex = -1
      for (let index = 0; index < lyricList.length; index++) {
        const lyric = lyricList[index]
        if (currentTime <= lyric.timestamp) {
          currentIndex = index - 1
          break
        }
        currentIndex = lyricList.length - 1
      }
      // 给当前歌词添加active
      const activeList = lyricUlDOM.querySelectorAll('li.active')
      activeList.forEach((_) => {
        _.className = ''
      })
      lyricUlDOM.children.item(currentIndex).className = 'active'
      // 让歌词一直在中间 > 7行
      if (currentIndex > 7) {
        lyricUlDOM.style.transform = `translateY(-${(currentIndex - 7)*30}px)`
      } else {
        lyricUlDOM.style.transform = `translateY(0px)`
      }
    })
  }
}

/** 初始化播放器 */
function initAudio() {
  // 设置初始声音 30%
  const audio = document.getElementById('audio')
  audio.volume = 0.3
}

(function(){
  initAudio()
  fetchLrc()
})()
